﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using ActiveStory.IO.XmlElementNames;

namespace ActiveStory.IO
{
    public class XmlActiveStoryProjectReader : IActiveStoryProjectReader
    {
        #region IActiveStoryProjectReader Members
        /// <summary>
        /// Parses the given project file and returns a string[] with the following:
        /// 0:ProjectName, 1:PageCounter, 2:PageLookupTableFileLocation, 3:DefaultCanvasWidth
        /// 4:DefaultCanvasHeight, 5:DefaultCanvasColor
        /// </summary>
        /// <param name="filename">The name of the file to read.</param>
        /// <returns></returns>
        public string[] ParseFile(string filename)
        {
            string[] result = new string[6];
            XmlReaderSettings xrs = new XmlReaderSettings();
            xrs.CloseInput = true;
            XmlReader xr = XmlReader.Create(filename, xrs);

            xr.ReadStartElement(ProjectFileXmlNames.RootElement);

            xr.ReadStartElement(ProjectFileXmlNames.ProjectNameElement);
            result[0] = xr.ReadContentAsString();
            xr.ReadEndElement();

            xr.ReadStartElement(ProjectFileXmlNames.PageCounterElement);
            result[1] = xr.ReadContentAsString();
            xr.ReadEndElement();

            xr.ReadStartElement(ProjectFileXmlNames.PageLookupFileLocElement);
            result[2] = xr.ReadContentAsString();
            xr.ReadEndElement();

            xr.ReadStartElement(ProjectFileXmlNames.DefaultCanvasWidthElement);
            result[3] = xr.ReadContentAsString();
            xr.ReadEndElement();

            xr.ReadStartElement(ProjectFileXmlNames.DefaultCanvasHeightElement);
            result[4] = xr.ReadContentAsString();
            xr.ReadEndElement();

            try                                             //New feautres for 2.0, putting in try catch to allow back compat with older versions.
            {
                xr.ReadStartElement(ProjectFileXmlNames.DefaultCanvasColorElement);
                result[5] = xr.ReadContentAsString();
            }
            catch
            {
                result[5] = System.Windows.Media.Colors.White.ToString();           //Default Canvas color was always white for pre-2.0, so just return that.
            }
            //xr.ReadEndElement();
            xr.Close();
            return result;
        }

        #endregion
    }
}
